package br.ufpb.di.ppgi.util.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;

public class Criptografia {
	
	public static String base64Encoder(String s) {
		return new Base64().encodeToString(s.getBytes());
	}
	public static String base64EncoderPlus(String s) {
		return base64Encoder(new StringBuilder(base64Encoder(s)).append(123).reverse().append(123).toString());
	}
	
	public static String base64DecoderPlus(String s) {
		try {
			return base64Decoder(new StringBuilder(base64Decoder(s)).delete(0, 3).reverse().delete(0, 3).toString());
		} catch(NullPointerException ex) {
			return null;
		}
	}
	
	public static String base64Decoder(String s) {
		return new String(new Base64().decode(s));
	}
	
	public static String md5Encode(String s) {
		return stringHexa(md5EncodeData(s));
	}
	
	public static byte[] md5EncodeData(String s) {
		return gerarHash(s, "md5");
	}
	
	private static byte[] gerarHash(String frase, String algoritmo) {
		try {
			MessageDigest md = MessageDigest.getInstance(algoritmo);
			md.update(frase.getBytes());
			return md.digest();
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}
	
	private static String stringHexa(byte[] bytes) {
		if (bytes == null)
			return "";
		StringBuilder s = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			int parteAlta = ((bytes[i] >> 4) & 0xf) << 4;
			int parteBaixa = bytes[i] & 0xf;
			if (parteAlta == 0) s.append('0');
			s.append(Integer.toHexString(parteAlta | parteBaixa));
		}
		return s.toString();
	}
}
